package com.ccp.dev.workflow.bpmutil;

import org.flowable.bpmn.model.BpmnModel;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.image.exception.FlowableImageException;
import org.flowable.image.impl.DefaultProcessDiagramGenerator;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * ClassDescribe:
 *  流程图生成工具类
 * @author :wangcheng
 * Date: 2019-05-27
 */
public class ImageGenerator {
    /**
     * 创建图片
     * @param bpmnModel 模型对象
     * @return 图片
     */
    public static BufferedImage createImage(BpmnModel bpmnModel) {
        ProcessDiagramGenerator diagramGenerator = new DefaultProcessDiagramGenerator();
        return diagramGenerator.generatePngImage(bpmnModel, 1.0);
    }

    /**
     * 创建图片
     * @param bpmnModel 模型对象
     * @param scaleFactor 比例因子
     * @return 图片
     */
    public static BufferedImage createImage(BpmnModel bpmnModel, double scaleFactor) {
        ProcessDiagramGenerator diagramGenerator = new DefaultProcessDiagramGenerator(scaleFactor);
        return diagramGenerator.generatePngImage(bpmnModel, scaleFactor);
    }

    /**
     * 为图片创建
     * @param image 图片对象
     * @param imageType 图片类型
     * @return 字节数据
     */
    public static byte[] createByteArrayForImage(BufferedImage image, String imageType) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, imageType, out);

        } catch (IOException e) {
            throw new FlowableImageException("Error while generating byte array for process image", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException ignore) {
                // Exception is silently ignored
            }
        }
        return out.toByteArray();
    }
}
